package main

import "fmt"

//#link: https://leetcode-cn.com/problems/reverse-string-ii/
func main() {
	s := "abcd"
	k := 2
	fmt.Println(reverseStr(s, k))
}

func reverseStr(s string, k int) string {
	sBytes := []byte(s)
	sLen := len(s)
	mod := sLen % (2 * k)

	for i := 0; i < sLen-mod; i += 2 * k {
		reverseChar(sBytes[i : i+k])
	}

	//反转前k个
	if mod >= k && mod < 2*k {
		reverseChar(sBytes[sLen-mod : sLen-mod+k])
	}

	//全部反转
	if mod < k {
		reverseChar(sBytes[sLen-mod:])
	}
	return string(sBytes)
}

func reverseChar(target []byte) {
	for i := 0; i < len(target)>>1; i++ {
		target[i], target[len(target)-1-i] = target[len(target)-1-i], target[i]
	}
}
